<template>
  <div>
    <el-card>
      <el-row type="flex" justify="center" align="center">
        <el-col :span="10" style="margin-left: 80px">
          <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
        </el-col>
        <el-col :span="4" style="margin-left: 100px;line-height: 130px">
          <h1>--></h1>
        </el-col>
        <el-col :span="10" style="line-height: 160px">
          <el-button plain type="danger" @click="excelClean" :disabled="upload_state">清空</el-button>
          <el-button plain type="primary" @click="excelUpload" :disabled="upload_state">上传至服务器</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" height="800px" border highlight-current-row stripe :header-cell-style="table_header" style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" align="center"/>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import {uploadExcel} from '@/api/fileUploadAndDownload'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: [],
      upload_state: true,
    }
  },
  methods: {
    table_header(row, column, rowIndex, columnIndex) {
      return 'background-color: #409EFF; color:white'
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (isLt1M) {
        return true
      }
      this.$message.warning('上传文件不能大于1M');
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results;
      this.tableHeader = header;
    },
	async excelClean(){
		this.tableData = []
		this.tableHeader = []
	},
    async excelUpload(){
      if (this.tableData.length === 0 || this.tableHeader.length === 0) return this.$message.error("数据为空，不能上传");
      const res = await uploadExcel({'headers':this.tableHeader, 'data': this.tableData});
      if (res.code !== 0) return this.$message.error("上传失败");
      this.$message.success("上传成功")
    }
  },
  watch: {
    tableData(new_val, old_val){
      this.upload_state = new_val.length <= 0;
    }
  }
}
</script>
